/*
Copyright (c) 2008, Oleg S. Estekhin
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of the copyright holders nor the names of its
      contributors may be used to endorse or promote products derived from this
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package ebml;

import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.text.Normalizer;

/** Utility methods for EBML element types. */
public final class ElementTypes {

    private static final Charset UTF_8 = Charset.forName("UTF-8");


    private ElementTypes() {
    }


    /**
     * Returns the minimum number of bytes required to encode the specified value as a signed integer.
     *
     * @param value the value
     *
     * @return the minimum size of the value in the signed integer encoded form
     */
    public static int getMinimumSignedIntegerEncodedSize(long value) {
        if (value == 0L) {
            return 0;
        } else {
            long mask = 0xffffffffffffff80L;
            long expected = value < 0L ? mask : 0L;
            int encodedSize = 1;
            while (encodedSize < 8 && (mask & value) != expected) {
                mask <<= 8;
                expected <<= 8;
                encodedSize++;
            }
            return encodedSize;
        }
    }

    /**
     * Returns the minimum number of bytes required to encode the specified value as an unsigned integer.
     *
     * @param value the value
     *
     * @return the minimum size of the value in the unsigned integer encoded form
     */
    public static int getMinimumUnsignedIntegerEncodedSize(long value) {
        long mask = 0xffffffffffffffffL;
        int encodedSize = 0;
        while (encodedSize < 8 && (mask & value) != 0L) {
            mask <<= 8;
            encodedSize++;
        }
        return encodedSize;
    }

    /**
     * Returns the minimum number of bytes required to encode the specified value in the UTF-8 encoding.
     *
     * @param value the value
     *
     * @return the minimum size of the value in the UTF-8 encoding
     *
     * @throws NullPointerException if <code>value</code> is <code>null</code>
     */
    public static long getMinimumUTF8StringEncodedSize(String value) {
        if (value == null) {
            throw new NullPointerException("value is null");
        }
        if (value.length() == 0) {
            return 0;
        }
        if (!Normalizer.isNormalized(value, Normalizer.Form.NFC)) {
            value = Normalizer.normalize(value, Normalizer.Form.NFC);
        }
        CharsetEncoder encoder = UTF_8.newEncoder()
                .onMalformedInput(CodingErrorAction.REPORT)
                .onUnmappableCharacter(CodingErrorAction.REPORT);
        try {
            return encoder.encode(CharBuffer.wrap(value)).remaining();
        } catch (CharacterCodingException e) {
            throw new AssertionError(e);
        }
    }

}
